package com.skp.shaphan.ui.connectioncontrols;

import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumnModel;

public class EditButtonMouseListener implements MouseListener {
	private JTable parentTable;

	public EditButtonMouseListener(JTable parentTable) {
		this.parentTable = parentTable;
	}
	
	public void forwardEvent(MouseEvent e) {
		TableColumnModel columnModel = parentTable.getColumnModel();
		int column = columnModel.getColumnIndexAtX(e.getX());
		int row = e.getY() / parentTable.getRowHeight();
		
		if(row >= parentTable.getRowCount()) {
			return;
		}
		if(column >= parentTable.getColumnCount()) {
			return;
		}
		
		Object value = parentTable.getValueAt(row, column);
		System.out.println("forwardEvent value = " + value.getClass().getName() + " (" + row + ", " + column + ")");
		if(!(value instanceof JButton)) {
			return;
		}
		
		JButton button = (JButton)value;
		MouseEvent buttonEvent = (MouseEvent)SwingUtilities.convertMouseEvent(parentTable, e, button);
		button.dispatchEvent(buttonEvent);
		System.out.println("   Dispatching event");
		for(ActionListener l : button.getActionListeners()) {
			System.out.println("     listener - " + l.getClass().getName());
		}
		parentTable.repaint();
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		forwardEvent(e);
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		forwardEvent(e);
	}

	@Override
	public void mouseExited(MouseEvent e) {
		forwardEvent(e);
	}

	@Override
	public void mousePressed(MouseEvent e) {
		forwardEvent(e);
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		forwardEvent(e);
	}

}
